import wx from 'weixin-js-sdk'
import Api from '@/api/community/share.ts'
import { wxShareConfig } from '@/config/share'
import tools from '@/server/storage.server'

class WX {
  async getConfig () {
    // const back_url = tools.get('back-url')
    const url = window.location.href.split('#')[0]
    let { data } = await Api.wxConfig({
      url: url
    })
    if (data) {
      this.setWx(data)
    }
  }
  setWx (res: any) {
    const shareInfo = wxShareConfig()
    wx.config({
      debug: false,
      appId: res.appId,
      timestamp: res.timestamp,
      nonceStr: res.nonceStr,
      signature: res.signature,
      jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']
    })
    wx.ready(function () {
      const inviteCode = tools.get('my_invite_code')

      wx.onMenuShareTimeline({
        title: shareInfo.title, // 分享标题
        desc: shareInfo.desc, // 分享描述
        link: shareInfo.link + inviteCode, // 分享链接
        imgUrl: shareInfo.imgurl // 分享图标
      })

      wx.onMenuShareAppMessage({
        title: shareInfo.title, // 分享标题
        desc: shareInfo.desc, // 分享描述
        link: shareInfo.link + inviteCode, // 分享链接
        imgUrl: shareInfo.imgurl // 分享图标
      })

      wx.onMenuShareQQ({
        title: shareInfo.title, // 分享标题
        desc: shareInfo.desc, // 分享描述
        link: shareInfo.link + inviteCode, // 分享链接
        imgUrl: shareInfo.imgurl // 分享图标
      })
      wx.onMenuShareWeibo({
        title: shareInfo.title, // 分享标题
        desc: shareInfo.desc, // 分享描述
        link: shareInfo.link + inviteCode, // 分享链接
        imgUrl: shareInfo.imgurl // 分享图标
      })
      wx.onMenuShareQZone({
        title: shareInfo.title, // 分享标题
        desc: shareInfo.desc, // 分享描述
        link: shareInfo.link + inviteCode, // 分享链接
        imgUrl: shareInfo.imgurl // 分享图标
      })

    })
    wx.error(function (err: any) {
      alert(JSON.stringify(err))
    })

  }
}

export default new WX()
